#include <pthread.h>
#include <rid.h>
#include <stdint.h>
#include <stdio.h>

#include <fn85.h>
#include <rid_fn85.h>

#include <nit/list.h>
#include <nit/set.h>
#include <nit/map.h>

#include <oas.h>

#include "pum.h"
#include "global.h"
#include "user.h"
#include "care.h"

int
parse_arg_id(Rid user_id, const char *arg)
{
	size_t len;

	switch (rid_fn85_parse(user_id, arg, &len)) {
	case FN85_OKAY:
		return 0;
	case FN85_INVALID:
		fprintf(stderr,
			"Something wasn't a digit at index %zu in "
			"the user id.\n",
			len);
		break;
	case FN85_TOO_HIGH:
		fprintf(stderr,
			"Number became larger than possible at index %zu "
			"in the user id.\n",
			len);
		break;
	}

	return -1;
}

/* static int */
/* echo_act(Rid self, const Rid sender, void *msg, void *local, Oas_sys *sys) */
/* { */
/* 	Pum_val *val = msg; */

/* 	if (val) { */
/* 		rid_set(val->id, NULL); */
/* 		oas_msg(sys, self, sender, val); */
/* 		return 0; */
/* 	} */

/* 	return 1; */
/* } */

/* static int */
/* echo_add(Oas_sys *sys) */
/* { */
/* 	Rid id; */
/* 	Rid_fn85 str; */

/* 	rid_set(id, NULL); */
/* 	rid_fn85(str, id); */

/* 	if (oas_add(sys, id, NULL, NULL, NULL, echo_act, NULL) < 0) { */
/* 		fprintf(stderr, "Failed to add echo actor"); */
/* 		return -1; */
/* 	} */

/* 	printf("Echo id %s\n", str); */
/* 	return 0; */
/* } */

Rid care_id = { 37, 182, 236, 135, 251, 224, 14, 16, 251, 224, 14, 16, 251, 224,
		14, 16 };

Rid focus_id = { 47, 142, 9, 85, 251, 224, 14, 16, 251, 224, 14, 16, 251, 224,
		 14, 16 };

int
main(int argc, char *argv[])
{
	Rid user_id;
	Oas_sys sys;

	if (argc < 2)
		rid_set(user_id, NULL);
	else if (parse_arg_id(user_id, argv[1]) < 0)
		return 1;

	if (oas_init(&sys, NULL, NULL) < 0) {
		fprintf(stderr, "Failed to init Oas.\n");
		return 1;
	}

	if (global_init(&sys) < 0) {
		fprintf(stderr, "Failed to init global data.\n");
		oas_dispose(&sys);
		return 1;
	}

	/* if (echo_add(&sys) < 0) { */
	/* 	global_dispose(&sys); */
	/* 	oas_dispose(&sys); */
	/* 	return 1; */
	/* } */

	if (care_add(&sys, care_id, focus_id) < 0) {
		global_dispose(&sys);
		oas_dispose(&sys);
		return 1;
	}


	if (!user_add(&sys, user_id))
		oas_wait(&sys);

	global_dispose(&sys);
	oas_dispose(&sys);
	return 0;
}
